<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    Based on "Weighted Blended Order-Independent Transparency"
    By Morgan McGuire and Louis Bavoil 
    http://jcgt.org/published/0002/02/09/
-->
<html>
<head>
    <title>PicoGL.js: Order-independent Transparency</title>
    <meta charset="utf-8">
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Order-independent Transparency
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/oit.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <script type="x-shader/vs" id="vertex-accum">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec3 normal;
        layout(location=3) in vec4 color;
        layout(location=4) in mat4 modelMatrix;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };       
        
        out vec3 vPosition;
        out vec2 vUV;
        out vec3 vNormal;
        flat out vec4 vColor;

        void main() {
            vec4 worldPosition = modelMatrix * position;
            vPosition = worldPosition.xyz;
            vUV = uv;
            vNormal = (modelMatrix * vec4(normal, 0.0)).xyz;
            vColor = vec4(color.r, color.g, color.b, color.a);
            gl_Position = uViewProj * worldPosition;
        }
    </script>
    <script type="x-shader/fs" id="fragment-accum">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };

        uniform sampler2D uTexture;
        
        in vec3 vPosition;
        in vec2 vUV;
        in vec3 vNormal;
        flat in vec4 vColor;

        layout(location=0) out vec4 accumColor;
        layout(location=1) out float accumAlpha;

        float weight(float z, float a) {
            return clamp(pow(min(1.0, a * 10.0) + 0.01, 3.0) * 1e8 * pow(1.0 - z * 0.9, 3.0), 1e-2, 3e3);
        }

        void main() {
            vec3 position = vPosition.xyz;
            vec3 normal = normalize(vNormal.xyz);
            vec2 uv = vUV;

            vec4 baseColor = vColor * texture(uTexture, uv);
            vec3 eyeDirection = normalize(uEyePosition.xyz - position);
            vec3 lightVec = uLightPosition.xyz - position;
            vec3 lightDirection = normalize(lightVec);
            vec3 reflectionDirection = reflect(-lightDirection, normal);
            float nDotL = max(dot(lightDirection, normal), 0.0);
            float diffuse = nDotL;
            float ambient = 0.2;
            float specular = pow(max(dot(reflectionDirection, eyeDirection), 0.0), 20.0);

            vec4 color = vec4((ambient + diffuse + specular) * baseColor.rgb, vColor.a);
            color.rgb *= color.a;
            float w = weight(gl_FragCoord.z, color.a);
            accumColor = vec4(color.rgb * w, color.a);
            accumAlpha = color.a * w;
        }
    </script>
    <script type="x-shader/vs" id="vertex-quad">
        #version 300 es

        layout(location=0) in vec4 aPosition;
        
        void main() {
            gl_Position = aPosition;
        }
    </script>

    <script type="x-shader/fs" id="fragment-blend">
        #version 300 es
        precision highp float;

        uniform sampler2D uAccumulate;
        uniform sampler2D uAccumulateAlpha;
        out vec4 fragColor;
        void main() {
            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            vec4 accum = texelFetch(uAccumulate, fragCoord, 0);
            float a = 1.0 - accum.a;
            accum.a = texelFetch(uAccumulateAlpha, fragCoord, 0).r;
            fragColor = vec4(a * accum.rgb / clamp(accum.a, 0.001, 50000.0), a);
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();

        var NEAR = 0.1;
        var FAR = 10.0;
        var NUM_SPHERES = 32;
        var NUM_PER_ROW = 8;
        var RADIUS = 0.6;

        var canvas = document.getElementById("gl-canvas");

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        if (!utils.testExtension("EXT_color_buffer_float")) {
            document.body.innerHTML = "This example requires extension EXT_color_buffer_float which is not supported on this system."
        }
        
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var app = PicoGL.createApp(canvas)
        .clearColor(0.0, 0.0, 0.0, 1.0)
        .blend()
        .depthMask(false)
        .floatRenderTargets();

        var timer = app.createTimer();

        var spheres = new Array(NUM_SPHERES);
        var sphereColorData = new Uint8Array(NUM_SPHERES * 4);
        var modelMatrixData = new Float32Array(NUM_SPHERES * 16);

        for (var i = 0; i < NUM_SPHERES; ++i) {
            var angle = 2 * Math.PI * (i % NUM_PER_ROW) / NUM_PER_ROW;
            var x = Math.sin(angle) * RADIUS;
            var y = Math.floor(i / NUM_PER_ROW) / (NUM_PER_ROW / 4) - 0.75;
            var z = Math.cos(angle) * RADIUS;
            spheres[i] = {
                scale: [0.8, 0.8, 0.8],
                rotate: [0, 0, 0], // Will be used for global rotation
                translate: [x, y, z],
                modelMatrix: mat4.create()
            };

            sphereColorData.set(vec4.fromValues(
                Math.floor(Math.sqrt(Math.random()) * 256),
                Math.floor(Math.sqrt(Math.random()) * 256),
                Math.floor(Math.sqrt(Math.random()) * 256),
                128
            ), i * 4);
        }

        // ACCUMULATION PROGRAM
        var accumVsSource = document.getElementById("vertex-accum").text.trim();
        var accumFsSource = document.getElementById("fragment-accum").text.trim();
        var accumProgram = app.createProgram(accumVsSource, accumFsSource);

        var accumulateTarget = app.createTexture2D(app.width, app.height, { 
            type: PicoGL.FLOAT 
        });
        var accumulateAlphaTarget = app.createTexture2D(app.width, app.height, { 
            type: PicoGL.FLOAT 
        });
        var accumBuffer = app.createFramebuffer()
        .colorTarget(0, accumulateTarget)
        .colorTarget(1, accumulateAlphaTarget);

        // BLEND PROGRAM
        var blendVsSource = document.getElementById("vertex-quad").text.trim();
        var blendFsSource = document.getElementById("fragment-blend").text.trim();
        var blendProgram = app.createProgram(blendVsSource, blendFsSource);

        // INSTANCED SPHERE GEOMETRY
        var sphere = utils.createSphere({radius: 0.5});
        var positions = app.createVertexBuffer(PicoGL.FLOAT, 3, sphere.positions);
        var uv = app.createVertexBuffer(PicoGL.FLOAT, 2, sphere.uvs);
        var normals = app.createVertexBuffer(PicoGL.FLOAT, 3, sphere.normals);
        var indices = app.createIndexBuffer(PicoGL.UNSIGNED_SHORT, 3, sphere.indices);

        // PER-INSTANCE COLORS AND MODEL MATRICES
        var colors = app.createVertexBuffer(PicoGL.UNSIGNED_BYTE, 4, sphereColorData);
        var modelMatrices = app.createMatrixBuffer(PicoGL.FLOAT_MAT4, modelMatrixData);

        var sphereArray = app.createVertexArray()
        .vertexAttributeBuffer(0, positions)
        .vertexAttributeBuffer(1, uv)
        .vertexAttributeBuffer(2, normals)
        .instanceNormalizedAttributeBuffer(3, colors)
        .instanceAttributeBuffer(4, modelMatrices)
        .indexBuffer(indices);

        // QUAD GEOMETRY
        var quadPositions = app.createVertexBuffer(PicoGL.FLOAT, 2, new Float32Array([
            -1, 1,
            -1, -1,
            1, -1,
            -1, 1,
            1, -1,
            1, 1,
        ]));

        var quadArray = app.createVertexArray()
        .vertexAttributeBuffer(0, quadPositions);

        // UNIFORM DATA
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, NEAR, FAR);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(0, 0.8, 2);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var lightPosition = vec3.fromValues(0.5, 1, 2); 

        // UNIFORM BUFFER
        var sceneUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .set(2, lightPosition)
        .update();


        window.onresize = function() {
            app.resize(window.innerWidth, window.innerHeight);
            accumBuffer.resize();

            mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);
            mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
            sceneUniforms.set(0, viewProjMatrix).update();
        };

        
        utils.loadImages(["img/webgl-logo.png"], function(images) {
            // CREATE TEXTURE
            var texture = app.createTexture2D(images[0], { flipY: true });

            var accumDrawCall = app.createDrawCall(accumProgram, sphereArray)
            .uniformBlock("SceneUniforms", sceneUniforms)
            .texture("uTexture", texture);

            var blendDrawCall = app.createDrawCall(blendProgram, quadArray)
            .texture("uAccumulate", accumBuffer.colorAttachments[0])
            .texture("uAccumulateAlpha", accumBuffer.colorAttachments[1]);

            var rotationMatrix = mat4.create();

            function draw() {
                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }

                timer.start();

                for (var i = 0, len = spheres.length; i < len; ++i) {
                    spheres[i].rotate[1] += 0.002;

                    utils.xformMatrix(spheres[i].modelMatrix, spheres[i].translate, null, spheres[i].scale);
                    mat4.fromYRotation(rotationMatrix, spheres[i].rotate[1]);
                    mat4.multiply(spheres[i].modelMatrix, rotationMatrix, spheres[i].modelMatrix)

                    modelMatrixData.set(spheres[i].modelMatrix, i * 16);
                }
                modelMatrices.data(modelMatrixData);

                // ACCUMULATION
                app.drawFramebuffer(accumBuffer)
                .blendFuncSeparate(PicoGL.ONE, PicoGL.ONE, PicoGL.ZERO, PicoGL.ONE_MINUS_SRC_ALPHA)
                .clear();
                accumDrawCall.draw()
                
                // BLEND
                app.defaultDrawFramebuffer()
                .blendFunc(PicoGL.ONE, PicoGL.ONE_MINUS_SRC_ALPHA)
                .clear();
                blendDrawCall.draw();
                
                timer.end(); 
                                
                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        });

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
